use axum::http::{HeaderName, HeaderValue};
use headers::{Error, Header};
use std::sync::LazyLock;
use crate::ToError;

#[derive(Clone, Debug, PartialEq)]
pub struct RefreshToken(pub String);

static REFRESH_TOKEN: LazyLock<HeaderName> =
    LazyLock::new(|| HeaderName::from_static("refresh-token"));
impl Header for RefreshToken {
    fn name() -> &'static HeaderName {
        &REFRESH_TOKEN
    }

    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
        values
            .next()
            .and_then(|v| v.to_str().ok()?.parse().ok())
            .map(RefreshToken)
            .to_err(Error::invalid)
    }

    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
        let value = self
            .0
            .as_str()
            .parse()
            .expect("Refresh-Token错误");
        values.extend(std::iter::once(value));
    }
}